package com.fzdy.dataplatform.mongodb;

import com.alibaba.fastjson.JSON;
import com.fzdy.dataplatform.core.common.Check;
import com.fzdy.dataplatform.core.vo.Page;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


@Component("mongodbmanager")
public class MongoDBManager {

//    private static MongoDBManager manager;

    @Value("${spring.data.mongodb.host}")
    private String address;
    @Value("${spring.data.mongodb.port}")
    private int port;
    private String dataBase;
    private String collection;

    MongoClient mongoClient;
    MongoDatabase mongoDatabase;
    MongoCollection<Document> mongoCol;


    public void getMongoCon(String dataBase, String collection) {
        MongoClientOptions.Builder builder=MongoClientOptions.builder();
        builder.connectTimeout(3000);
        MongoClientOptions mongoClientOptions = builder.build();
        mongoClient = new MongoClient(new ServerAddress(address, port),mongoClientOptions);
        mongoDatabase = mongoClient.getDatabase(dataBase);
        mongoCol = mongoDatabase.getCollection(collection);

    }

    /**
     * 创建集合
     */
    public void mongodbCreate() {

        mongoDatabase.createCollection(collection);
    }

    /**
     * 向mongodb添加数据
     */

    public void mongdbAddDoc(Document doc) {

        mongoCol.insertOne(doc);
    }

    /**
     * 关闭mongodb连接
     */

    public void mongoClose() {

        mongoClient.close();
    }



    /**
     * 向mongodb添加多条数据
     */

    public void mongdbAddDocs(List<Document> list) {

        mongoCol.insertMany(list);


    }

    /**
     * 向mongodb删除一条数据
     *
     * @param basic 查询条件 //注意Bson的几个实现类，BasicDBObject, BsonDocument,
     *              BsonDocumentWrapper, CommandResult, Document, RawBsonDocument
     */

    public DeleteResult mougdbDel(BasicDBObject basic) {

        Bson filter = basic;
        DeleteResult dResult = mongoCol.deleteOne(filter);

        return dResult;
    }

    /**
     * 向mongodb删除多条数据
     *
     * @param basic 查询条件 //注意Bson的几个实现类，BasicDBObject, BsonDocument,
     *              BsonDocumentWrapper, CommandResult, Document, RawBsonDocument
     */

    public DeleteResult mougdbDels(BasicDBObject basic) {

        Bson filter = basic;
        DeleteResult dResult = mongoCol.deleteMany(filter);

        return dResult;
    }

    /**
     * 向mongodb修改单条数据
     *
     * @param filter
     * @param update
     * @return
     */

    public UpdateResult mongdbUpdateOne(Bson filter, Bson update) {

        UpdateResult result = mongoCol.updateOne(filter, update);
        return result;
    }

    /**
     * 向mongodb修改单条数据
     *
     * @param filter
     * @param update
     * @return
     */

    public UpdateResult mongdbUpdateMany(Bson filter, Bson update) {


        UpdateResult result = mongoCol.updateMany(filter, update);
        return result;
    }

    /**
     * mongodb根据固定条件查询数据查询数据
     */

    public List<Document> mongdbQuery(Bson bson) {


        List<Document> array = new ArrayList<>();
        FindIterable<Document> findy = mongoCol.find(bson);
        MongoCursor<Document> cursor = findy.iterator();
        while (cursor.hasNext()) {

            array.add(cursor.next());
        }
        return array;
    }

    /**
     * mongodb根据BasicDBObject中的固定条件查询数据查询数据
     */

    public List<Document> mongdbQuery(BasicDBObject obj) {

        List<Document> array = new ArrayList<>();
        Bson bson = obj;
        FindIterable<Document> findy = mongoCol.find(bson);
        MongoCursor<Document> cursor = findy.iterator();
        while (cursor.hasNext()) {

            array.add(cursor.next());
        }
        return array;
    }

    /**
     * 根据key和value值查询数据
     *
     * @param key   查询字段
     * @param value 查询内容
     * @return
     */

    public List<Document> mongdbQuery(String key, Object value) {

        List<Document> array = new ArrayList<>();
        Bson bson = new BasicDBObject().append(key, value);
        FindIterable<Document> findy = mongoCol.find(bson);
        MongoCursor<Document> cursor = findy.iterator();
        while (cursor.hasNext()) {

            array.add(cursor.next());
        }
        return array;
    }

    public List<DeviceData> mongdbQueryPageBysnAndCreatedate(String sn, String createdate, Page page) {
        BasicDBObject snBson = new BasicDBObject("devicesn", sn);
        Pattern pattern = Pattern.compile("^.*" + createdate + ".*$", Pattern.CASE_INSENSITIVE);
        Bson sortBson;
        if (!Check.checkStringNull(page.getOrders())){
            String[] orders = page.getOrders().split(" ");
            int val;
            if (orders[1].equals("asc")){
                val=1;
            }else {
                val=-1;
            }
             sortBson = new BasicDBObject().append(orders[0], val);
        }else{
            sortBson=new BasicDBObject().append("createdate", -1);
        }
        snBson.put("createdate", pattern);
        FindIterable<Document> findy = mongoCol.find(snBson).limit(page.getPageSize())
                .skip((page.getPageCurrent() - 1) * page.getPageSize()).sort(sortBson);

        List<DeviceData> array = new ArrayList<>();
        MongoCursor<Document> cursor = findy.iterator();
        while (cursor.hasNext()) {
            Document a = cursor.next();
            DeviceData ktv = JSON.parseObject(a.toJson(), DeviceData.class);
            array.add(ktv);
        }
        return array;
    }


    /**
     * 向mongodb查询所有数据
     */

    public List<Document> mongdbQuerys() {

        List<Document> array = new ArrayList<>();
        FindIterable<Document> findAll = mongoCol.find();
        MongoCursor<Document> corsor = findAll.iterator();
        while (corsor.hasNext()) {

            array.add(corsor.next());
        }
        return array;

    }

    public Long mongCountBysnAndCreatedate(String sn, String createdate) {
        BasicDBObject snBson = new BasicDBObject("devicesn", sn);
        Pattern pattern = Pattern.compile("^.*" + createdate + ".*$", Pattern.CASE_INSENSITIVE);
        snBson.put("createdate", pattern);
        return mongoCol.count(snBson);
    }

    public List<DeviceData> mongGetAllBysnAndCreatedate(String sn, String createdate) {
        BasicDBObject snBson = new BasicDBObject("devicesn", sn);
        Pattern pattern = Pattern.compile("^.*" + createdate + ".*$", Pattern.CASE_INSENSITIVE);
        snBson.put("createdate", pattern);
        Bson sortBson = new BasicDBObject().append("createdate", 1);
        FindIterable<Document> findy = mongoCol.find(snBson).sort(sortBson);
        List<DeviceData> array = new ArrayList<>();
        MongoCursor<Document> cursor = findy.iterator();
        while (cursor.hasNext()) {
            Document a = cursor.next();
            DeviceData ktv = JSON.parseObject(a.toJson(), DeviceData.class);
            array.add(ktv);
        }
        return array;
    }
    public List<DeviceData> ceshi() {
//        List sn=null;
//        BasicDBObject obj=new BasicDBObject("$in",sn);
//        BasicDBObject snobj=new BasicDBObject("sn",obj);

//        List<BasicDBObject> aggreList = new ArrayList<BasicDBObject>();
//        BasicDBObject cdate = new BasicDBObject("$substr", Arrays.asList("$createdate", 0, 10));
//        //第一次group by ，对设备和日期两个属性进行分组，不统计
//        BasicDBObject id1 = new BasicDBObject("sn","$devicesn");
//        id1.put("cdate",cdate);
//        BasicDBObject group1 = new BasicDBObject("_id", id1);
//        aggreList.add(new BasicDBObject("$group",group1));
//
//        //第二次group by ,将第一次的group by 的结果进行日期分组，统计次数
//        BasicDBObject id2 = new BasicDBObject("cdata","$_id.cdate");
//        BasicDBObject group2 = new BasicDBObject("_id", id2);
//        group2.put("count",new BasicDBObject("$sum",1));
//        aggreList.add(new BasicDBObject("$group",group2));
//
//        AggregateIterable<Document> docIterable  = mongoCol.aggregate(aggreList);
//        List<JSONObject> reportBydates=new

//        group.put()
//        System.out.println(group);
//
//        Pattern pattern = Pattern.compile("^.*" + createdate + ".*$", Pattern.CASE_INSENSITIVE);
//        snBson.put("createdate", pattern);
//        Bson sortBson = new BasicDBObject().append("createdate", 1);
//        FindIterable<Document> findy = mongoCol.find(snBson).sort(sortBson);
        
//        List<DeviceData> array = new ArrayList<>();
//        MongoCursor<Document> cursor = findy.iterator();
//        while (cursor.hasNext()) {
//            Document a = cursor.next();
//            DeviceData ktv = JSON.parseObject(a.toJson(), DeviceData.class);
//            array.add(ktv);
//        }
//        return array;
        return null;
    }


}

